const { OPERATION_IS_NOT_ALLOWED } = require("../config/error")
const permissionService = require("../service/permission.service")

const verifyPermission = async (ctx, next) => {
    // const {
    //     id
    // } = ctx.user
    // const {
    //     momentId
    // } = ctx.params

    // const result = await permissionService.check(momentId, id)
    // if (!result) {
    //    return ctx.app.emit('error', OPERATION_IS_NOT_ALLOWED, ctx)
    // }

    const {
        id
    } = ctx.user

    const keyName = Object.keys(ctx.params)[0]
    const resourceId = ctx.params[keyName]
    const resourceName = keyName.replace('Id', '')

    const result = await permissionService.check(resourceName, resourceId, id)
    if (!result) {
        return ctx.app.emit('error', OPERATION_IS_NOT_ALLOWED, ctx)
    }

    await next()
}

module.exports = {
    verifyPermission
}